/**
 * 认证 Composable - 可移植的登录逻辑
 */
import { ref, type Ref } from 'vue'
import { wailsAPI } from '../../utils/wails-api'
import type { LoginConfig } from '../../types/api'
import { createLogger } from '../../utils/logger'

const logger = createLogger('auth')

export interface LoginCredentials {
  loginId: string
  loginKey: string
}

export interface LoginResult {
  success: boolean
  message?: string
}

export interface UseAuthReturn {
  loading: Ref<boolean>
  error: Ref<string>
  login: (credentials: LoginCredentials) => Promise<LoginResult>
  saveCredentials: (credentials: LoginCredentials, remember?: boolean) => Promise<void>
  loadCredentials: () => Promise<LoginCredentials | null>
  clearCredentials: () => Promise<void>
  clearError: () => void
}

export function useAuth(): UseAuthReturn {
  const loading = ref(false)
  const error = ref('')

  /**
   * 登录验证
   */
  const login = async (credentials: LoginCredentials): Promise<LoginResult> => {
    loading.value = true
    error.value = ''

    logger.debug('开始登录验证', { loginId: credentials.loginId })

    try {
      const result = await wailsAPI.login(credentials.loginId, credentials.loginKey)

      // 适配返回格式：result.result 表示是否成功，result.msg 表示消息
      const success = result.result === true
      const message = result.msg || '登录失败'

      if (!success) {
        error.value = message
        logger.warn('登录失败', { loginId: credentials.loginId, message })
      } else {
        logger.info('登录成功', { loginId: credentials.loginId })
      }

      return { success, message }
    } catch (err) {
      const message = err instanceof Error ? err.message : '登录异常'
      error.value = message
      logger.error('登录异常', { loginId: credentials.loginId, error: message })
      return { success: false, message }
    } finally {
      loading.value = false
    }
  }

  /**
   * 保存登录凭据
   */
  const saveCredentials = async (credentials: LoginCredentials, remember = true): Promise<void> => {
    const config: LoginConfig = {
      loginId: credentials.loginId,
      loginKey: remember ? credentials.loginKey : '',
      rememberCredentials: remember
    }
    await wailsAPI.saveAppConfig('login', config)
    logger.debug('保存登录凭据', { loginId: credentials.loginId, remember })
  }

  /**
   * 加载保存的凭据
   */
  const loadCredentials = async (): Promise<LoginCredentials | null> => {
    try {
      const config = (await wailsAPI.getAppConfig('login')) as LoginConfig
      if (config?.loginId && config.rememberCredentials) {
        return {
          loginId: config.loginId,
          loginKey: config.loginKey || ''
        }
      }
      return null
    } catch {
      return null
    }
  }

  /**
   * 清除保存的登录凭据
   */
  const clearCredentials = async (): Promise<void> => {
    const config: LoginConfig = {
      loginId: '',
      loginKey: '',
      rememberCredentials: false
    }
    await wailsAPI.saveAppConfig('login', config)
    logger.debug('清除登录凭据')
  }

  /**
   * 清除错误信息
   */
  const clearError = (): void => {
    error.value = ''
  }

  return {
    loading,
    error,
    login,
    saveCredentials,
    loadCredentials,
    clearCredentials,
    clearError
  }
}

